package com.example.module.module.user.service;

import com.example.module.module.user.entity.User;
import com.example.module.module.user.mapper.UserMapper;
import com.example.module.utils.BaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User getById(BigInteger userId) {

        return userMapper.getById(userId);
    }

    public User extractById(Long userId) {

        return userMapper.extractById(userId);
    }

    public Integer insert(User entity) {

        return userMapper.insert(entity);
    }

    public Integer update(User entity) {

        return userMapper.update(entity);
    }

    public Integer delete(Long id, Integer updateTime) {

        return userMapper.delete((int)(System.currentTimeMillis() / 1000), id);
    }

    public User register(String phone, String password, String name,String avatar) {

        validateParameters(phone,password,name,avatar);
        if (userMapper.getByPhone(phone) != null) {
            throw new RuntimeException("手机号已注册");
        }
        User user = new User();
        user.setPhone(phone);
        user.setPassword(BaseUtils.md5(password)); // 改为MD5加密
        user.setName(name);
        user.setAvatar(avatar);
        user.setCreateTime((int)(System.currentTimeMillis() / 1000));
        user.setUpdateTime((int)(System.currentTimeMillis() / 1000));
        user.setIsDeleted(0);
        userMapper.insert(user);
        return user;
    }

    private void validateParameters(String phone, String password, String name,  String avatar) {
        if (phone == null || phone.isEmpty()) {
            throw new RuntimeException("电话不能为空");
        }
        if (password == null || password.isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }
        if (name == null || name.isEmpty()) {
            throw new RuntimeException("名字不能为空");
        }
        if (avatar == null || avatar.isEmpty()) {
            throw new RuntimeException("头像不能为空");
        }
    }

    public User login(String phone, String password) {
        User user = userMapper.getByPhone(phone);
        String md5Password = BaseUtils.md5(password); // 计算输入密码的MD5
        if (user == null || !md5Password.equals(user.getPassword())) { // 改为MD5比较
            throw new RuntimeException("手机号或密码错误");
        }
        return user;
    }
}
